<template>
    <div>
        <leftBar></leftBar>
        <div class="activity-right"  style="padding-top:20px;">
            <h3>新增代购礼包</h3>
            <el-form  ref="form" :rules="rules"   :model="form" label-width="110px">
                <div class="form">
                    <el-form-item label="礼包名称:" prop="goodsName">
                        <el-input style="width:400px" v-model="form.goodsName" type="text" placeholder="请输入商品名称" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="礼包编码:" prop="goodsCode">
                        <el-input style="width:400px" v-model="form.goodsCode" type="text" placeholder="请输入商品编码" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="礼包介绍:" prop="goodsDesc">
                        <el-input type='textarea' :rows="5" style="width:400px" v-model="form.goodsDesc"></el-input>
                    </el-form-item>
                    <el-form-item label="礼包价格:" prop="goodsPrice">
                        <el-input style="width:400px" v-model="form.goodsPrice" type="text" placeholder="请输入商品原价" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="礼包排序:" prop="sort">
                        <el-input style="width:400px" v-model="form.sort" type="text" placeholder="请输入商品序号" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="礼包卖点:" prop="usp">
                        <el-input style="width:400px" v-model="form.usp" type="text" placeholder="请输入一句话卖点" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="礼包库存:" prop="stockNum">
                          <el-input style="width:400px" v-model="form.stockNum" type="text" placeholder="请输入商品库存数量" clearable></el-input>
                    </el-form-item>
                    <el-form-item prop="goodsImg" label="礼包图片:" class="uploadWrap" v-loading="uploadLoading">
                        <div class="prevImg" :key="item.id" v-for="(item,index) in form.goodsImg" v-if="form.goodsImg.length > 0">
                            <img height="200" :src="item" alt="">
                            <i class="el-icon-back" title="位置前进一位" v-if="index != 0" @click="goToPrev(index)"></i>
                            <i class="el-icon-error" @click="deleteImgList(index)"></i>
                        </div>
                        <template v-if="form.goodsImg.length < 9">
                            <div class="upload">
                                <input class="file" name="file" type="file" accept="image/png,image/gif,image/jpeg" multiple @change="uploadImg($event)" />
                                <i class="el-icon-plus"></i>
                            </div>
                        </template>
                        <p class="red" style="margin-top:10px;line-height:1.5">
                            <small>请选择活动图片上传(最多9张)</small>
                        </p>
                        <p class="red" style="margin-top:10px;line-height:1.5">
                            <small>建议尺寸：宽度不小于400</small>
                        </p>
                    </el-form-item>
                </div>
            </el-form> 
            <section class="submit"> 
                <el-button type="primary"  @click="submit">确定</el-button>
                <el-button type="primary" style="margin-left:10px" @click="$router.go(-1)">返回</el-button>                        
            </section> 
        </div> 
    </div>
</template>
<script>
    import leftBar from '../commonComponents/leftBar.vue';
   // import addGoodsItem from '../commonComponents/addGoodsItem.vue';
    import { getQiniuToken, qiniuBaseUrl, addGiftPack} from '../../data/postData';
    export default {
       
        components:{
            leftBar
        },
        data(){
            return{
                user: JSON.parse(localStorage.getItem('ddaigoUser')),      
                getTagByStoreNo: null,          
                form:{
                    goodsName: '',
                    goodsCode:'',
                    sort:'',
                    usp:'',
                    goodsPrice: '',
                    storeNo:'',
                    goodsPic:'',
                    goodsDesc:'',
                    goodsImg:[],
                    stockNum:''

                },
                disabled:false,
                uploadLoading:false,
                goodsSize:[
                    {
                        size:'S',
                        num:'0'
                    },
                    {
                        size:'M',
                        num:'0'
                    },
                    {
                        size:'L',
                        num:'0'
                    } 
                ],
                dataForm:null,
                activityStatus:'',
                activityArr:[],
                status:true,
                disabled:false,
                addGoodsVal:null,
                paramList:[],
                brandArray:[],
                isShow1:false,
                soltArray:[
                    {
                        value: '0',
                        label:'上架'
                    }, {
                        value:'1',
                        label:'下架'
                    }
                ],
                categoryId:'',
                goodsItem:[],
                selGoodItemVal:[],
                isShowGoodsItem:false,
                goodsItem1:[],
                goodsItem2:[],
                goodsItem3:[],
                textarea:'',
                discount: false,
                coverUploadLoading: false,
                uploadLoading: false,
                rules: {
                    goodsName: [
                        { required: true, message: '请输入商品名称', trigger: 'blur' },
                    ],
                    goodsPrice: [
                        { required: true, message: '请输入商品原价', trigger: 'blur' },
                    ],
                    goodsCode: [
                        { required: true, message: '请输入商品编码', trigger: 'blur' },
                    ],
                    sort: [
                        { required: true, message: '请输入商品序号', trigger: 'blur' },
                    ],
                    stockNum: [
                        { required: true, message: '请输入商品库存', trigger: 'blur' },
                    ],
                    goodsDetail: [
                        { required: true, message: '请输入商品介绍', trigger: 'blur' },
                    ],
                    goodsColor: [
                        { required: true, message: '请输入商品颜色/规格', trigger: 'blur' },
                    ],
                    goodsImg: [
                        { required: true, message: '请上传商品图片', trigger: 'blur' },
                    ],
                    
                   
                },
            }
        },
        mounted(){
          
        },
        methods:{
            handleClear(){
                // this.form.discountRate = ''
                // this.form.discountPrice = ''
            },
            getActivity(){
                this.getActivity()
            },
            //获取活动列表
            getActivity(){
                let params = {
                    "data":{
                        "id":''+this.form.activityId,
                        "storeNo":this.user.storeNo
                    }
                }
                console.log(params,'----params')
                this.$fetch.post(getActivityDetail,params).then(res=>{
                    this.activityStatus = res.data.status
                    console.log(this.activityStatus,'hahha')
                })
            },
            clickImage(index){
                console.log(this.form.goodsUrl)
                console.log(index)
                this.imageNum = index
                this.isShow1 = true
            },
            closeImage(){
                this.isShow1 =false
            },
            addgoodsSize(e){
                this.goodsSize.push({
                    size:'',
                    num:'0'
                })
            },
            delColor(idx){
                console.log(idx)
                this.paramList.splice(idx,1)
            },
            message(msg,icon){
                this.$message({
                    message: msg,
                    type: icon ? icon : 'success'
                });
            },
            submit(){
                if(this.form.goodsCode === ''){
                    this.$message({
                        message: '商品编码不能为空',
                        type: 'warning',
                        duration:1000
                    });
                } else if(this.form.goodsName === '') {
                    this.$message({
                        message: '商品名称不能为空',
                        type: 'warning',
                        duration:1000
                    });
                } else if(this.form.goodsPrice === '') {
                    this.$message({
                        message: '商品价格不能为空',
                        type: 'warning',
                        duration:1000
                    });
                }else if(this.form.sort === '') {
                    this.$message({
                        message: '商品排序不能为空',
                        type: 'warning',
                        duration:1000
                    });
                }else if(this.form.goodsImg.length < 1) {
                    this.$message({
                        message: '商品图片至少1张',
                        type: 'warning',
                        duration:1000
                    });
                }else if(this.form.stockNum === '') {
                    this.$message({
                        message: '商品库存不能为空',
                        type: 'warning',
                        duration:1000
                    });
                }else{
                    var params = {
                        "data": {
                            "goodsCode": this.form.goodsCode,
                            "goodsName": this.form.goodsName,
                            "goodsPic": this.form.goodsImg[0],
                            "goodsDesc": this.form.goodsDesc,
                            "goodsColor": '代购礼包',
                            "goodsPrice": this.form.goodsPrice,
                            "storeNo": this.user.storeNo,
                            "goodsDetail": this.form.goodsImg.join(','),
                            "sort": +this.form.sort,
                            "usp": this.form.usp,
                            "goodsImg": this.form.goodsImg,
                            "stockNum": +this.form.stockNum,
                            "soldout": '2'
                        }
                    }
                    this.$fetch.post(addGiftPack, params).then(res=>{
                        this.$message({
                            message: res.message,
                            type: 'success',
                            duration:1000
                        })
                        setTimeout(()=>{
                            this.$router.go(-1)
                        },1200)
    
                    }).catch(err=>{
                        this.$message({
                            message: err.message,
                            type: 'warning',
                            duration:1000
                        })
                    })
                }
            },
		    uploadImg(e){
                const that = this;
                var files = e.target.files;
                for (let i = 0; i < files.length; i++) {
                    let width, height;
                    let reader = new FileReader();
                    reader.onload = function(e) {
                        var image = new Image();
                        image.onload = function() {
                            width = image.width;
                            height = image.height;
                            if (width >= 400) {
                                that.uploadLoading = true;
                                that.$http.get(getQiniuToken, {
                                    params: {
                                        wxUid: "",
                                        wxSid: ""
                                    }
                                }).then(res1 => {
                                        let config = {
                                            headers: {
                                                "Content-Type":
                                                "multipart/form-data"
                                            }
                                        };
                                        let formdata = new FormData(); //创建form对象
                                        formdata.append( "file", files[i], files[i].name);
                                        formdata.append("chunk", "0"); //断点传输
                                        formdata.append("chunks", "1");
                                        formdata.append("token", res1.data.uptoken);
                                        console.log(formdata, "formdata");
                                        that.$http.post("http://up-z1.qiniup.com", formdata, config).then(res2 => {
                                            if (res2.data.key != "") {
                                                that.form.goodsImg.push(
                                                    qiniuBaseUrl + res2.data.key + "?imageMogr2/thumbnail/400000@"
                                                );
                                                that.form.goodsImg = that.form.goodsImg.slice(0,9)
                                                that.$message({
                                                    title: "提示",
                                                    message: "图片上传成功",
                                                    type: "success"
                                                });
                                                that.uploadLoading = false;
                                            }
                                        });
                                    });
                            } else {
                                that.$message({
                                    title: "提示",
                                    message: "上传图片尺寸要求宽度不小于400",
                                    type: "warning"
                                });
                            }
                        };
                        image.src = e.target.result;
                    };
                    reader.readAsDataURL(files[i]);
                }                                     
            },
            deleteImgList(idx){
                this.form.goodsImg.splice(idx, 1);
            },
            goToPrev(idx){
                let newImg = this.form.goodsImg.slice();
                if (idx > 0) {
                    let now = newImg[idx].toString();
                    let prev = newImg[idx - 1].toString();
                    newImg[idx] = prev;
                    newImg[idx - 1] = now;
                    console.log("goodsUrl", newImg);
                }
                this.form.goodsImg = newImg;
            }
        }
    }
</script>

<style scoped lang="less">
    @import url('../../style/activity.less');
    @import url('../../style/goods.less');
    .activity-right {
        h3{
            margin-bottom:20px
            
        }
    }
    .stock{

       display:inline-block;
       li{
           float: left;
           padding:0 10px;
           input{
               width:40px;
           }
       }
    }
    .addGoods-1{
        margin-top:20px;
        border-bottom:2px solid #000;
    }
    .addColor{
        margin-bottom:10px;
        margin-left:80%;
    }
    .submit{
        margin-left:0;
        margin-top:50px;
    }
    .form{
         margin-bottom:20px;
        border-bottom:2px solid #000;
    }
</style>